package com.unionbigdata.teaching.sevice.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unionbigdata.teaching.constant.ServiceStateEnum;
import com.unionbigdata.teaching.entity.ServiceEntity;
import com.unionbigdata.teaching.mapper.ServiceMapper;
import com.unionbigdata.teaching.sevice.ServiceService;
import com.unionbigdata.teaching.util.PageMapperUtil;
import com.unionbigdata.teaching.vo.req.ServicePageReq;
import com.unionbigdata.teaching.vo.resp.ServiceEntityRespVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Objects;

@Service
public class ServiceServiceImpl extends ServiceImpl<ServiceMapper, ServiceEntity>
        implements ServiceService {

    @Override
    public ServiceEntityRespVO getById(Long id) {
        ServiceEntity serviceEntity = baseMapper.selectById(id);
        if (Objects.isNull(serviceEntity)) {
            throw new RuntimeException("没有服务信息");
        }
        ServiceEntityRespVO respVO = new ServiceEntityRespVO();
        BeanUtils.copyProperties(serviceEntity, respVO);
        respVO.setStateDes(ServiceStateEnum.getDescByStatus(serviceEntity.getState()));
        return respVO;
    }

    @Override
    public Page<ServiceEntityRespVO> page(ServicePageReq req) {
        Page<ServiceEntity> page = new Page<>(req.getCurrent(), req.getPageSize());

        Page<ServiceEntity> entityPage = baseMapper.selectPage(page, new LambdaQueryWrapper<ServiceEntity>()
                .eq(!Objects.isNull(req.getState()), ServiceEntity::getState, req.getState())
                .like(StringUtils.isNotBlank(req.getDes()), ServiceEntity::getDes, req.getDes())
                .orderByDesc(ServiceEntity::getUpdateTime));
        Page<ServiceEntityRespVO> voPage = PageMapperUtil.mapPage(entityPage, ServiceEntityRespVO.class);
        if (CollectionUtils.isEmpty(voPage.getRecords())) {
           return voPage;
        }
        voPage.getRecords().forEach(serviceEntityRespVO -> {
            serviceEntityRespVO.setStateDes(ServiceStateEnum.getDescByStatus(serviceEntityRespVO.getState()));
        });
        return voPage;
    }
}
